package com.sy.simpleegg.platform.whm.cmd

import android.util.Log
import com.sy.logger.Logger
import java.io.ByteArrayInputStream
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.Charset
import java.util.Locale
import java.util.Random

object CmdAssistant {

    private const val TAG = "Tranfer"

    private var msgNumber = 0

    private var billOrderMsgNumber = 246
    val random: String
        /**
         * 获取随机数[0, 255]
         * @return 16进制字符串
         */
        get() = try {
            val random = Random()
            val rd = random.nextInt(256)
            var hexStr = Integer.toHexString(rd).uppercase(Locale.getDefault())
            while (hexStr.length < 2) {
                hexStr = "0$hexStr"
            }
            hexStr
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d(TAG, "获取随机数异常：" + e.message)
            "00"
        }

    /**
     * 字符串转16进制
     * @param str
     * @param byteLen 长度（字节）
     * @return 16进制字符串
     */
    fun str2hex(str: String, byteLen: Int): String? {
        var result: String? = null
        try {
            val chars = "0123456789ABCDEF".toCharArray()
            val sb = StringBuilder("")
            val bs = str.toByteArray()
            var bit: Int
            for (i in bs.indices) {
                bit = bs[i].toInt() and 0x0f0 shr 4
                sb.append(chars[bit])
                bit = bs[i].toInt() and 0x0f
                sb.append(chars[bit])
                //            sb.append(' ');
            }
            while (sb.length < byteLen * 2) {
                sb.append(chars[0])
            }
            result = sb.toString().trim { it <= ' ' }
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("字符串转16进制异常：" + e.message)
        }
        return result
    }

    fun str2hex(str: String): String? {
        var result: String? = null
        try {
            val chars = "0123456789ABCDEF".toCharArray()
            val sb = StringBuilder("")
            val bs = str.toByteArray()
            var bit: Int
            for (i in bs.indices) {
                bit = bs[i].toInt() and 0x0f0 shr 4
                sb.append(chars[bit])
                bit = bs[i].toInt() and 0x0f
                sb.append(chars[bit])
                //            sb.append(' ');
            }
            //            while(sb.length() < byteLen*2){
//                sb.append(chars[0]);
//            }
            result = sb.toString().trim { it <= ' ' }
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("字符串转16进制异常：" + e.message)
        }
        return result
    }

    /**
     * 字符串转字节数组
     * @param str
     * @return
     */
    fun hexToByteArray(str: String): ByteArray? {
        var str = str
        var result: ByteArray? = null
        try {
            var hexLen = str.length
            if (hexLen % 2 == 1) {
                hexLen++
                result = ByteArray(hexLen / 2)
                str = "0$str"
            } else {
                result = ByteArray(hexLen / 2)
            }
            var j = 0
            var i = 0
            while (i < hexLen) {
                result[j] = hexToByte(str.substring(i, i + 2))
                j++
                i += 2
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "字符串转字节数组异常：" + e.message)
        }
        return result
    }

    /**
     *
     * @param hexStr
     * @return
     */
    fun hexToByte(hexStr: String): Byte {
        return hexStr.toInt(16).toByte()
    }

    /**
     * 字节数组累加
     * @param bytes
     * @return
     */
    fun addByte(bytes: ByteArray): Int {
        var rs = 0
        try {
            val byInput = ByteArrayInputStream(bytes)
            for (i in bytes.indices) {
                rs += byInput.read()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "字节数组累加异常：" + e.message)
        }
        return rs
    }

    fun highLow(count: Int): String {
        val big = count and 0xFF00 shr 8
        val little = count and 0xFF
        var bigStr = Integer.toHexString(big)
        if (bigStr.length < 2) {
            bigStr = "0$bigStr"
        }
        var littleStr = Integer.toHexString(little)
        if (littleStr.length < 2) {
            littleStr = "0$littleStr"
        }
        return (bigStr + littleStr).uppercase(Locale.getDefault())
    }

    fun convertHighLow(dec: Int): String {
        var dec = dec
        var hex = ""
        while (dec != 0) {
            var h = Integer.toString(dec and 0xff, 16)
            if (h.length and 0x01 == 1) h = "0$h"
            hex = hex + h
            dec = dec shr 8
        }
        while (hex.length < 4) {
            hex += "0"
        }
        return hex.uppercase(Locale.getDefault())
    }

    /**
     * 16进制String转String
     * @param hexStr
     * @return
     */
    fun hexToStr(hexStr: String): String {
        var result = ""
        try {
            val charArray = hexStr.toCharArray()
            var i = 0
            while (i < charArray.size) {
                val st = "" + charArray[i] + "" + charArray[i + 1]
                val ch = st.toInt(16).toChar()
                result = result + ch
                i = i + 2
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "16进制转字符串异常：" + e.message)
        }
        return result
    }

    fun hexStringToString(s: String?): String? {
        var s = s
        if (s == null || s == "") {
            return null
        }
        s = s.replace(" ", "")
        val baKeyword = ByteArray(s.length / 2)
        for (i in baKeyword.indices) {
            try {
                baKeyword[i] = (0xff and s.substring(i * 2, i * 2 + 2).toInt(16)).toByte()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        try {
            s = String(baKeyword, charset("UTF-8"))
            ""
        } catch (e1: Exception) {
            e1.printStackTrace()
        }
        return s
    }

    fun byteArrayToHexStr(byteArray: ByteArray?): String? {
        if (byteArray == null) {
            return null
        }
        val hexArray = "0123456789ABCDEF".toCharArray()
        val hexChars = CharArray(byteArray.size * 2)
        for (j in byteArray.indices) {
            val v = byteArray[j].toInt() and 0xFF
            hexChars[j * 2] = hexArray[v ushr 4]
            hexChars[j * 2 + 1] = hexArray[v and 0x0F]
        }
        return String(hexChars)
    }

    fun getBillOrderMsgNumber(): String {
        var hexStr = Integer.toHexString(billOrderMsgNumber).uppercase(Locale.getDefault())
        while (hexStr.length < 2) {
            hexStr = "0$hexStr"
        }
        if (billOrderMsgNumber >= 255) {
            billOrderMsgNumber = 246
        } else {
            billOrderMsgNumber += 1
        }
        return hexStr
    }

    fun currentBillOrderMsgNumber(): String {
        return Integer.toHexString(billOrderMsgNumber).uppercase(Locale.getDefault())
    }

    fun calculateHex(hexStr: String): Int {
        var hexStr = hexStr
        val target: String
        var result = 0
        try {
            while (hexStr.length % 2 != 0) {
                hexStr = "0$hexStr"
            }
            target = hexStr
            val len = target.length

//            for (int i = 0; i < len / 2; i++) {
//                result += Integer.parseInt(target, 16);
//            }
            result = target.toInt(16)
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("计算十六进制")
        }
        return result
    }

    fun char2ByteArr(c: Char): ByteArray {
        val b = ByteArray(2)
        b[0] = (c.code and 0xFF00 shr 8).toByte()
        b[1] = (c.code and 0xFF).toByte()
        return b
    }

    fun bytesTochars(bytes: ByteArray): CharArray {
        val cs = Charset.forName("UTF-8")
        val bb = ByteBuffer.allocate(bytes.size)
        bb.put(bytes).flip()
        val cb = cs.decode(bb)
        return cb.array()
    }

    fun charsTobytes(chars: CharArray): ByteArray {
        val cs = Charset.forName("UTF-8")
        val cb = CharBuffer.allocate(chars.size)
        cb.put(chars)
        cb.flip()
        val bb = cs.encode(cb)
        return bb.array()
    }

    fun charToByte(c: Char): ByteArray {
        val b = ByteArray(2)
        b[0] = (c.code and 0xFF00 shr 8).toByte()
        b[1] = (c.code and 0xFF).toByte()
        return b
    }

    fun byteToChar(b: ByteArray): Char {
        val hi = b[0].toInt() and 0xFF shl 8
        val lo = b[1].toInt() and 0xFF
        return (hi or lo).toChar()
    }

    fun getMsgNumber(): String{
        var hexStr = Integer.toHexString(msgNumber).uppercase(Locale.getDefault())
        while (hexStr.length < 2) {
            hexStr = "0$hexStr"
        }
        if (msgNumber >= 245) {
            msgNumber = 0
        } else {
            msgNumber += 1
        }
        return hexStr
    }
}
